<!-- 打卡 -->
<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500" draggable @closed="handlerClosed">
    <el-form :model="clockinform">
      <el-form-item label="日期" size="large"> {{ clockinform.clockinDate }} </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" size="large">{{ clockinform.userNick }}（{{ clockinform.userName }}）</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门" size="large">{{ clockinform.deptName }}</el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="false">
        <el-col :span="12">
          <el-form-item label="工号" size="large">
            <el-input v-model="clockinform.number" readonly size="large" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位" size="large">
            <el-input v-model="clockinform.post" readonly size="large" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="">
        <el-radio-group v-model="clockinform.clockinCategory" size="large">
          <el-radio v-for="(item, idx) in clockinCategoryList" :key="idx" :value="item.dictValue" :disabled="isDisabled[idx]">{{ item.dictLabel }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="打卡时间" size="large">
        <el-time-picker v-model="clockinform.clockinTime" placeholder="打卡时间" size="large" format="HH:mm" />
      </el-form-item>
      <el-form-item label="　　　　" size="large" style="text-align: left">
        <el-alert title="补卡规则：每月只能补卡2次！周期为上月26日至本月25日，（不要超过次数）" :closable="false" type="error" effect="dark" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handlerClickBtnCancel">取消</el-button>
        <el-button type="primary" @click="handlerClickBtnSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { formatDate } from '../../utils'
import { useUsersStore } from '../../stores'
import http from '../../http'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const timer = ref<any>(null)
const emits = defineEmits(['submitSuccessed'])
const dialogTitle = computed(() => {
  let title = '打'
  if (clockinform.clockinCategory === '0') {
    title = '早卡'
  } else if (clockinform.clockinCategory === '1') {
    title = '晚卡'
  }
  title = ' ' + clockinform.clockinDate + ' ' + title
  if (isComp.value) {
    title = '补' + title
  }
  return title
})

interface IClockinCategory {
  dictValue: number
  dictLabel: string
}

defineProps({
  clockinCategoryList: {
    type: Array<IClockinCategory>,
    required: true,
    default: () => [{ dictValue: 0 }],
  },
})
const date = new Date()
// 是补打卡
const isComp = ref(false)
const clockinform = reactive({
  id: null,
  userId: -1,
  userName: '',
  userNick: '',
  number: '',
  deptId: '',
  deptName: '',
  post: '',
  clockinDate: formatDate(date, 'yyyy-MM-dd'),
  clockinTime: date,
  clockinCategory: '',
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: '',
})
const defaultObj = ref<any>({})

//  是否已有打卡记录
const hasClockIn = ref(-1)
const isDisabled = ref([false, false])
/**
 * 打开对话框并初始化数据
 *
 * @param objectValue 包含日期、默认打卡类别、打卡类别列表和是否完成打卡的对象
 * @param objectValue.date 日期对象
 * @param objectValue.defaultClockinCategory 默认打卡类别
 * @param objectValue.clockinCategoryList 打卡类别列表
 * @param objectValue.isComp 是否完成打卡
 * @param objectValue.checkIsClockIn 检查是否已经打卡
 * @param objectValue.clickInUser 点击打卡的用户信息
 */
const openDialog = async (objectValue: { date: Date; defaultClockinCategory: string; clockinCategoryList: IClockinCategory[]; isComp: boolean; checkIsClockIn: number; clickInUser: any }) => {
  // clockinCategoryList.value = objectValue.clockinCategoryList
  // console.log('objectValue', objectValue)
  isComp.value = objectValue.isComp || false
  const currentUser = objectValue.clickInUser || useUsersStore().getAllState()
  if (currentUser) {
    clockinform.userId = currentUser.userId || -1
    clockinform.deptId = currentUser.deptId || ''
    clockinform.deptName = currentUser.deptName || ''
    clockinform.userName = currentUser.username || ''
    clockinform.userNick = currentUser.nickName || ''
    clockinform.deptName = currentUser.deptName || ''
  }
  clockinform.clockinCategory = objectValue.defaultClockinCategory
  clockinform.clockinDate = formatDate(objectValue.date, 'yyyy-MM-dd')

  clockinform.clockinTime = new Date(clockinform.clockinDate + ' ' + formatDate(new Date(), 'HH:mm:ss'))
  // console.log('clockinform.clockinTime', clockinform.clockinTime)
  defaultObj.value = objectValue
  dialogVisible.value = true
  isDisabled.value = [false, false]

  if (objectValue.checkIsClockIn !== -1) {
    clockinform.clockinCategory = objectValue.checkIsClockIn.toString()
    hasClockIn.value = objectValue.checkIsClockIn
    if (objectValue.checkIsClockIn === 1) {
      isDisabled.value[0] = true
    } else if (objectValue.checkIsClockIn === 0) {
      isDisabled.value[1] = true
    }
  }
  // console.log('clockinform.clockinCategory', clockinform.clockinCategory)
  // console.log('objectValue.checkIsClockIn', objectValue.checkIsClockIn)

  // clearInterval(timer.value)
  // if (!isComp.value) {
  //   timer.value = setInterval(() => {
  //     clockinform.clockinTime = new Date()
  //   }, 1000)
  // }
}

/**
 * 处理点击提交按钮的异步函数
 */
const handlerClickBtnSubmit = async () => {
  const h = clockinform.clockinTime.getHours()
  const s = clockinform.clockinTime.getMinutes()
  const clockinDate = new Date(clockinform.clockinDate)
  clockinDate.setHours(h)
  clockinDate.setMinutes(s)

  const params = {
    id: null,
    clockinCategory: clockinform.clockinCategory,
    clockinDate: formatDate(clockinDate, 'yyyy-MM-dd'),
    clockinTime: formatDate(clockinDate, 'yyyy-MM-dd HH:mm:ss'),
  }
  if (isComp.value) {
    Object.assign(params, { clockinStatus: 1 })
  }
  // console.log('params', params)
  // return
  const res = await http({
    method: 'POST',
    path: '/dev-api/oa/clockin',
    params: { ...clockinform, ...params },
  })
  if (res.code === 200) {
    dialogVisible.value = false
    ElMessage({
      message: '打卡成功！',
      grouping: true,
      type: 'success',
    })
    emits('submitSuccessed')
  } else {
    ElMessage({
      message: '打卡失败！',
      grouping: true,
      type: 'error',
    })
  }
}

const handlerClosed = () => {
  clearInterval(timer.value)
}

/**
 * 重置表单
 *
 * 该函数用于重置表单的数据。首先获取默认对象值和当前用户信息，
 * 如果当前用户存在，则更新表单中与用户相关的信息；
 * 然后设置表单的打卡类别和打卡日期；
 * 如果isComp.value为true，则更新打卡时间为当前日期和时间。
 */
const formReset = () => {
  const objectValue = defaultObj.value
  const currentUser = useUsersStore().getAllState()
  if (currentUser) {
    clockinform.userId = currentUser.userId || -1
    clockinform.deptId = currentUser.deptId || ''
    clockinform.deptName = currentUser.deptName || ''
    clockinform.userName = currentUser.username || ''
    clockinform.userNick = currentUser.nickName || ''
    clockinform.deptName = currentUser.deptName || ''
  }
  clockinform.clockinCategory = objectValue.defaultClockinCategory
  clockinform.clockinDate = formatDate(objectValue.date, 'yyyy-MM-dd')
  isDisabled.value = [false, false]
  if (isComp.value) {
    clockinform.clockinTime = new Date(clockinform.clockinDate + ' ' + formatDate(new Date(), 'HH:mm:ss'))
  }
}
const handlerClickBtnCancel = () => {
  formReset()
  dialogVisible.value = false
}
onMounted(() => {})

defineExpose({
  openDialog,
})
</script>
<style lang="scss" scoped></style>
